/* Form.cpp
Michael Zahniser, 2008

Function definitions for the Form class.
*/

#include "Form.h"

#include <ncurses.h>



// Get the named field. Create it if it does not exist.
Field &Form::GetField(const string &label)
{
	list<Field>::iterator it = fields.begin();
	for( ; it != fields.end(); ++it)
		if(it->Label() == label)
			return *it;
	
	fields.push_back(Field(label));
	
	return fields.back();
}



bool Form::Run()
{
	list<Field>::iterator it = fields.begin();
	int row = 0;
	while(it != fields.end())
	{
		Draw();
		move(row, it->Width());
		
		int key = getch();
		if(key == KEY_UP)
		{
			if(it == fields.begin())
				return false;
			--it;
			--row;
		}
		else if(it->HandleKey(key))
		{
			++it;
			++row;
		}
	}
	
	return true;
}



void Form::Draw() const
{
	int y = 0;
	for(list<Field>::const_iterator it = fields.begin(); it != fields.end(); ++it, ++y)
	{
		it->Draw(y);
		clrtoeol();
	}
}
